package gptma.fo.controler.employee;

import gptma.bo.model.task.Imputation;
import gptma.bo.services.employee.EmployeeServices;
import gptma.bo.services.task.TaskServices;
import gptma.bo.util.GptmaUtils;
import gptma.fo.bean.ImputationBean;
import gptma.fo.cdi.ViewScoped;
import gptma.fo.controler.ResultPage;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.ejb.EJB;
import javax.inject.Named;
import org.primefaces.event.DateSelectEvent;

/**
 * 
 * @author xcl
 */
@Named
@ViewScoped
public class WeeklyImputationsPage extends ResultPage<ImputationBean> implements
		Serializable {

	private static final long serialVersionUID = -4665963921480586428L;

	@EJB
	private TaskServices taskServices;

	@EJB
	private EmployeeServices employeeServices;

	private float weekConsumate;

	private Date date;

	public WeeklyImputationsPage() {
		this.date = new Date();
	}

	public String deleteImputation(Imputation toBeRemoved) {
		Calendar cal = Calendar.getInstance(Locale.FRANCE);
		cal.setTime(toBeRemoved.getDate());
		cal.add(Calendar.DATE, application.getImputationRemovalDayLimit());

		if (cal.getTime().before(new Date())) {
			addErrorMessageFromKey("impImputationDeleteDayLimit");
		} else {
			employeeServices.deleteImputation(toBeRemoved);
			initializeImputations(date);
			addInfoMessageFromKey("impImputationsDeleteOk");
		}

		return null;
	}

	public void initImputationsPage() {
		initializeImputations(date);
	}

	public void dateChanged(DateSelectEvent event) {
		initializeImputations(event.getDate());
	}

	private void initializeImputations(Date selectedDate) {
		Date[] dates = GptmaUtils.getEnclosingWeek(selectedDate);

		List<Imputation> imputations = employeeServices
				.findImputationsFromDates(user, dates[0], dates[1]);
		results = new ArrayList<ImputationBean>();

		float consolidated;
		float charge;
		weekConsumate = 0;
		for (Imputation imputation : imputations) {
			charge = imputation.getCharge();
			weekConsumate += charge;

			consolidated = taskServices.findConsolidatedCharge(
					imputation.getTask(), imputation.getDate());
			results.add(new ImputationBean(imputation, consolidated - charge));
		}
	}

	public String getImputationsPanelTitle() {
		Calendar cal = Calendar.getInstance(Locale.FRANCE);
		cal.setTime(date);

		return getLocalisedMessage("impImputationsSemaineTitle",
				cal.get(Calendar.WEEK_OF_YEAR));
	}

	public float getWeekConsumate() {
		return weekConsumate;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

}
